<!--
 @Date: 2025-06-30 17:40:03
 * @LastEditTime: 2025-07-15 10:50:46
-->
<template>
  <div class="deploy-form-plain-wrapper">
    <Form  layout="horizontal" class="deploy-form-plain" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" :model="form" :rules="rules" ref="formRef">
      <FormItem label="任务名称：" name="flowName" required>
        <Input v-model:value="form.flowName" placeholder="请输入任务名称" />
      </FormItem>
      <FormItem label="任务描述：" name="flowDesc">
        <Input v-model:value="form.flowDesc" placeholder="请输入任务描述" />
      </FormItem>

      <FormItem label="源数据源：" required class="source-form-item">
        <Row :gutter="16">
          <Col :span="11">
          <FormItem name="sourceType" style="flex:1; margin-bottom:0;">
            <Select
              v-model:value="form.sourceType"
              placeholder="请选择数据源类型"
              @change="changeSourceType"
              :filter-option="filterOption"
              show-search
              >
              <Select.Option :value="item.dbConfName" v-for="item in sourceTypeList" :key="item.dbConfId" :label="item.dbConfName">{{item.dbConfName}}</Select.Option>

            
            </Select>
          </FormItem>
          </Col>
          <Col :span="11">
          <FormItem name="source" style="flex:1; margin-bottom:0;">
            <Select 
              v-model:value="form.sourceId" 
              placeholder="请选择数据源" 
              @dropdownVisibleChange="getDataSourcePageInfo"
              :filter-option="filterOption"
              show-search
              >
              <Select.Option :value="item.db_id" v-for="item in sourceList" :key="item.db_id" :label="item.db_alias_name">{{item.db_alias_name}}</Select.Option>
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <a-divider style="margin: 4px 0" />
                <div
                  style="padding: 4px 8px; width: 100%"
                  @mousedown.prevent
                  @click.stop
                >
                  <a-flex
                    style="width: 100%; padding-left: 30px"
                    horizontal
                    justify="center"
                    align="center"
                  >
                    <span style="line-height: 35px">没找到？</span>
                    <a-button type="text" @click="openAddGroups">
                      <template #icon>
                        <plus-outlined />
                      </template>
                      创建数据
                    </a-button>
                  </a-flex>
                </div>
              </template> 
            </Select>
          </FormItem>
          </Col>
          <Col :span="2">   
          <Button type="link" @click="linkTest()">连接测试</Button>
          </Col>
        </Row>
      </FormItem>
      <FormItem label="程序执行节点：" name="macId" required>
        <div style="display: flex; gap: 8px;">
          <Select 
            v-model:value="form.macId" 
            :filter-option="filterOption"
            show-search
            placeholder="选择程序运行的主机" style="flex:1;">
            <Select.Option 
            :value="item.mac_id" 
            v-for="item in hostList" 
            :label="item.host_name"
            :key="item.mac_id">{{item.host_name}}</Select.Option>
            <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <a-divider style="margin: 4px 0" />
                <div
                  style="padding: 4px 8px; width: 100%"
                  @mousedown.prevent
                  @click.stop
                >
                  <a-flex
                    style="width: 100%; padding-left: 30px"
                    horizontal
                    justify="center"
                    align="center"
                  >
                    <span style="line-height: 35px">没找到？</span>
                    <Button type="text" @click="openaddHost">
                      <template #icon>
                        <plus-outlined />
                      </template>
                      添加主机
                    </Button>
                  </a-flex>
                </div>
              </template> 
          </Select>
          <Button type="link" @click="testLinkhost">连接测试</Button>
        </div>
      </FormItem>
      <FormItem label="选择目标库类型：" name="targetTypes" required>
        <Select  v-model:value="form.targetTypes" placeholder="点击进行选择（可多选）" mode="multiple" >
          <Select.Option :value="item.dbConfName" v-for="item in sourceTypeList" :key="item.dbConfId">{{item.dbConfName}}</Select.Option>
        </Select>
      </FormItem>
    </Form>
  </div>
  <div class="flex justify-center">
        <!-- <a-button type="primary" @click="prev" style="margin-right: 10px;">上一步</a-button> -->
        <a-button type="primary" @click="next">下一步</a-button>
       </div>

    <!-- 添加数据源 -->
    <addSourceForm
      v-if="openGroups"
      :open="openGroups"
      @update:open="closeGroups"
    />
    <addEditHost ref="addEditHostRef" @getTabData="getTabData" :ot="$t"></addEditHost>

</template>

<script setup>
import { ref, reactive,defineExpose,onMounted,defineComponent,defineEmits } from 'vue';
import { Form,FormItem, Input, Select, Button ,Row,Col,message} from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import * as http from '@/api/flow/createTask';
import * as flowhttp from '@/api/flow/index';
import { useStore } from 'vuex';
import addEditHost from "@DSG/components/AddHost"
import addSourceForm from "@/components/addSourceForm/index";
const store = useStore();

const openGroups = ref(false); //添加组

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render () {
    return this.vnodes;
  },
});
const formState = reactive({
  flowName: "",
  flowGroupId: undefined,
  flowDesc: "",
  flowType: 1,
  taskStype: undefined,
  taskTtype: undefined,
  taskSRC: undefined,
  taskSRCname: undefined,
  taskTAR: undefined,
  taskTARname: undefined,
  taskTarList: [0],
  type0: undefined,
  srcData0: undefined,
  taskName0: undefined,
  dbCustomName0: undefined,
  deployModel: 1,
  host: undefined,
  srcHost: undefined,
  tarHost: undefined,
  srcNodeNumber: undefined,
  isDeployBackflow: false,
  backFlowMode: 1,
});

const formRef = ref();
const form = reactive({
  flowName: '',
  flowDesc: '',
  sourceType: '',
  sourceId: '',
  macId: '',
  targetTypes: [],
});

const filterOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const sourceTypeList = ref([]);
const hostList = ref([]);
const sourceList = ref([]);
const selectRowSourceType = ref({});

const rules = {
  flowName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  sourceType: [
    { required: true, message: '请选择数据源类型', trigger: 'change' }
  ],
  sourceId: [
    { required: true, message: '请选择数据源', trigger: 'change' }
  ],
  macId: [
    { required: true, message: '请选择程序执行节点', trigger: 'change' }
  ],
  targetTypes: [
    { required: true, type: 'array', min: 1, message: '请选择目标库类型', trigger: 'change' }
  ]
};
const next =async () => {
  let res = await save()
  console.log(res,'res')
  if(res){
    emit('next')
  }
}
const prev = () => {
  emit('prev')
}
const testLinkhost = async () => {
  const selectedHost = hostList.value.find(host => host.mac_id === form.macId);
  if (!selectedHost) {
    message.warning('请先选择主机');
    return;
  }
  
  // try {
    const params = {
      ...selectedHost,
      userID: sessionStorage.getItem("userId")
    };
    
    const res = await flowhttp.verifyHost(params);
    if (res.code === "000000") {
      message.success('连接测试成功');
    } else {
      message.error('连接测试失败！');
    }
};
//连接测试
const linkTest = async () => {
  linkCommon()
};
//大数据连接测试
const biglinkCommon = async () => {

const item = typeDatas.value.find(
  (e) =>
    e.db_id == formState[oProps.dataSource] ||
    e.db_alias_name == formState[oProps.dataSource]
);

// item["userID"] = sessionStorage.getItem("userId");
// item.db_type = formState[oProps.type].split("|")[1];
console.log(newbigdata.value, newgroupId.value, 'typeDatastypeDatasssssssssssss')
let resBody = {}
resBody.clusterType = newbigdata.value.clusterType;
resBody.clusterVersion = newbigdata.value.clusterVersion;
resBody.clusterAliasName = newbigdata.value.clusterAliasName;
resBody.clusterFilePath = newbigdata.value.clusterFilePath;
resBody.kerberos = newbigdata.value.kerberos;
if (newbigdata.value.isdatahub) {
  resBody.isdatahub = newbigdata.value.isdatahub;
}
resBody.userKeyPath = newbigdata.value.userKeyPath;
resBody.kerberosKeyPath = newbigdata.value.kerberosKeyPath;
resBody.verifyUser = newbigdata.value.verifyUser;
resBody.verifyRegionName = newbigdata.value.verifyRegionName;
resBody.dataValue = newbigdata.value.dataValue;
resBody.uploadPath = newbigdata.value.uploadpa;
resBody.serviceName = newbigdata.value.serviceName;
// if(this.hostS[0].hostIp || this.hostS[0].hostName){
//   resBody.mapHost = JSON.stringify(this.hostS);
// }


const res = await http.startClusterConfig(resBody);
if (res.code == "000000") {
  message.success($t('baseForm.sourceTargetItem.testSuccess'));
  // saveDataSourceInfo(params);
} else {
  message.error($t('baseForm.sourceTargetItem.testFail'));
}
};
const linkCommon = async () => {
  console.log(form.sourceId, 'form.sourceId')
  const item = sourceList.value.find(
    (e) =>
      e.db_id === form.sourceId
  );

  item["userID"] = sessionStorage.getItem("userId");
  item.isTnsNameUpdate = false
  const res = await flowhttp.validatorDataSource({ ...item });
  if (res.code == "000000") {
    message.success('连接测试成功');
  } else {
    message.error('连接测试失败！');
  }
};
const save = () => {
  console.log('save')
 return formRef.value.validate().then(async res => {

   
    let status = await  saveCMFlowInfo()

    if(status.code == '000000'){
      return true
    }else{
      message.error(status.msg)
      return true
    }
  }).catch(err => {
   return false
  });
};
// 关闭弹框
const closeGroups = () => {
  openGroups.value = false;
};

const openAddGroups = (e) => {
  openGroups.value = true;
};

const addEditHostRef = ref(null)
const openaddHost = () => {
  // openHost.value = true;
  addEditHostRef.value.openAdd()
};
const getTabData = () => {
  // openHost.value = true;
  console.log('qqqqq')
};

const changeSourceType = (value) => {
  selectRowSourceType.value = sourceTypeList.value.find(item => item.dbConfName == value);
  form.sourceId=''
};

const saveCMFlowInfo =async () => {
  let params = {
    flowId:store.state.taskInfo.flowId,
    flowName: form.flowName,
    flowDesc: form.flowDesc,
    flowType:1,
    deployMode:'1',
    reserve4:form.sourceType,
    dbId:form.sourceId,
    macId:form.macId,
    reserve2:form.targetTypes.join(',')
  }
  let res = await http.saveCMFlowInfo(params);
  console.log(res);
  return res
};

// 获取数据源类型
const getDataBaseTypeInfo = async () => {
  let params = {
    userID:window.sessionStorage.getItem("userId"),
  }
  let res = await http.getDataBaseTypeInfo(params);
  try {
    sourceTypeList.value = res.data;
  } catch (error) {
    console.log(error);
    message.error(error);
  }
};
// 获取数据源列表
const getDataSourcePageInfo = async () => {
  let params = {
    userID:window.sessionStorage.getItem("userId"),
    groupId:selectRowSourceType.value.groupId,
    db_type:selectRowSourceType.value.dbConfName,
    userGroupId: sessionStorage.getItem("userGid"),
    engineID:''
    
  }
  let res = await http.getDataSourcePageInfo(params);
  try {
    sourceList.value = res.data.rows;
  } catch (error) {
    console.log(error);
    message.error(error);
  }
};
// 获取主机列表
const queryAllHostInfo = async () => {
  let params = {
    userID:window.sessionStorage.getItem("userId"),
  }
  let res = await http.queryAllHostInfo(params);
  try {
    hostList.value = res.data.rows;
  } catch (error) {
    console.log(error);
    message.error(error);
  }
};
const emit = defineEmits(['save','next','prev'])
// 获取回显信息
const queryCMFlowInfo = async () => {
  let params = {
    flowId:store.state.taskInfo.flowId,
  }
  let res = await http.queryCMFlowInfo(params);
  try{
    if(res.code == '000000' && res.data){
      form.flowName = res.data.flowName
      form.flowDesc = res.data.flowDesc
      form.sourceType = res.data.reserve4
      form.sourceId = res.data.dbId
      form.macId = res.data.macId
      form.targetTypes = res.data.reserve2.split(',')
    }
  }catch(error){
    console.log(error);
    message.error(error);
  }
}
onMounted(async () => {
  if(store.state.taskInfo.flowId){
    await queryCMFlowInfo()
  }else{
    store.commit('setFlowId',new Date().getTime());
  }
  await getDataBaseTypeInfo()
  // 如果已经有数据源类型，还需要回显数据源列表
  if (form.sourceType) {
    selectRowSourceType.value = sourceTypeList.value.find(item => item.dbConfName == form.sourceType);
    getDataSourcePageInfo()
  }
  queryAllHostInfo()
});
defineExpose({
  save
});
</script>

<style scoped>
.deploy-form-plain-wrapper {
  width: 100%;
  min-height: 480px;
  padding: 40px 0 24px 0;
  display: flex;
  justify-content: center;
}
.deploy-form-plain {
  min-width: 340px;
  max-width: 700px;
  width: 100%;
  margin-left: 0;
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  padding: 0;
}
:deep(.ant-form-item-label > label) {
  font-weight: 500;
  font-size: 15px;
}
.source-form-item{
    margin-bottom: 0 !important;
  }
@media (max-width: 900px) {
  .deploy-form-plain {
    min-width: 0;
    max-width: 100vw;
    margin-left: 0;
    padding: 0 4vw;
  }
  .deploy-form-plain-wrapper {
    justify-content: center;
  }
  
}
</style>